﻿using Cysharp.Threading.Tasks;
using System;
using UniRx;
using UnityEngine;

public class Portal : USaBehaviour
{
    [SerializeField, Tooltip("当前传送门编号")]
    public int id;

    [Space, SerializeField, Tooltip("关联的地图id")]
    public int targetSceneId;

    [SerializeField, Tooltip("目标传送门编号。当到达对应场景的传送门数量大于1时，与之对应的传送门编号")]
    public int targetId;

    /// <summary>
    /// 所在的场景id
    /// </summary>
    public int sceneId => SceneManager.currentScene.GetId();

    public Collider2D trigger
    {
        get
        {
            if (m_Trigger != null)
            {
                m_Trigger = GetComponent<Collider2D>();
                m_Trigger.isTrigger = true;
            }
            return m_Trigger;
        }
    }
    private Collider2D m_Trigger;

    /// <summary>
    /// 进入传送门
    /// </summary>
    public void Enter()
    {
        // 同场景传送
        if (targetSceneId == sceneId)
        {
            var portal = SceneOrganizer.instance.FindPortal(targetId);
            if (portal == null)
            {
                Debug.Log($"进入传送门失败：未找到目标传送门");
                return;
            }
            SceneOrganizer.playerInstance.transform.position = portal.transform.position;
        }
        // 不同场景传送
        else
        {
            IDisposable freezeListener = null;
            freezeListener = SceneManager.onLoadingStart.Subscribe(_ =>
            {
                SceneOrganizer.playerInstance.Freeze();
                freezeListener?.Dispose();
            });

            IDisposable hideListener = null;
            hideListener = SceneManager.onLoadingMaskEnabled.Subscribe(_ =>
            {
                SceneOrganizer.instance.GetPlayerSpawner().HidePlayer();
                hideListener?.Dispose();
            });

            IDisposable showListener = null;
            showListener = SceneManager.onLoadingMaskDisabled.Subscribe(_ =>
            {
                SceneOrganizer.instance.GetPlayerSpawner().ShowPlayer();
                var portal = SceneOrganizer.instance.FindPortal(targetId);
                SceneOrganizer.playerInstance.transform.position = portal.transform.position;
                showListener?.Dispose();
            });

            IDisposable thawListener = null;
            thawListener = SceneManager.onLoadingEnd.Subscribe(_ =>
            {
                SceneOrganizer.playerInstance.Thaw();
                thawListener?.Dispose();
            });

            SceneManager.LoadSceneAsync(targetSceneId).Forget();
        }
    }
}